<?php
/**
 * @package Joomla
 * @subpackage Jmonoslideshow
 * @copyright (C) 2010 - Matthieu BARBE - www.ccomca.com
 * @license GNU/GPL v2
 * 
 * Jmonoslideshow is a Joomla extension for Monoslideshow.
 *
 * Jmonoslideshow uses :
 * Monoslideshow (http://www.monoslideshow.com/)
 * Plupload (http://www.plupload.com/) by Moxicode Systems
 * json class by Michal Migurski, Matt Knapp, Brett Stimmerman
 * jquery a JavaScript Library (http://jquery.com/)
 * getid3 library (http://getid3.sourceforge.net/)
 * swfobject is an easy-to-use and standards-friendly method to embed Flash content, which utilizes one small JavaScript file (http://code.google.com/p/swfobject/)
 * Chained Selects jQuery Plugin (http://www.appelsiini.net/2010/jquery-chained-selects)
 *
 * Jmonoslideshow is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// import Joomla table library
jimport('joomla.database.table');

/**
 * Monoslideshow Table class
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class JmonoslideshowTableMedia extends JTable
{
	
	/**
	 * Constructor
	 *
	 * @param object Database connector object
	 */
	public function __construct(&$db) {
		parent::__construct('#__monoslideshow', 'id', $db);
	}
	
	/**
	 * Method to compute the default name of the asset.
	 * The default name is in the form `table_name.id`
	 * where id is the value of the primary key of the table.
	 *
	 * @return	string
	 * @since	1.6
	 */
	protected function _getAssetName() {
		$k = $this->_tbl_key;
		return 'com_jmonoslideshow.media.'.(int) $this->$k;
	}

	/**
	 * Get the parent asset id for the record
	 *
	 * @return	int
	 *
	 * @since	0.0.1
	 *
	 * @see		JTable::_getAssetParentId
	 */
	protected function _getAssetParentId($table = null, $id = null) 
	{
		// Initialise variables.
		$assetId = null;
		$db = $this->getDbo();

		// Build the query to get the asset id for the parent category.
		$query = $db->getQuery(true);
		$query->select('asset_id');
		$query->from('#__categories');
		$query->where('id = ' . (int)$this->catid);
		

		// Get the asset id from the database.
		$this->_db->setQuery($query);
		if ($result = $this->_db->loadResult()) 
		{
			return (int)$result;
		}
		else
		{
			return parent::_getAssetParentId($table, $id);
		}
	}
	
	
	/**
	* Overloaded bind function
	*
	* @acces public
	* @param array $hash named array
	* @return null|string	null is operation was satisfactory, otherwise returns an error
	* @see JTable:bind
	* @since 1.5
	*/
	function bind($array, $ignore = '')
	{
		// Bind the params
		if (isset($array['params']) && is_array($array['params'])) 
		{
			$registry = new JRegistry();
			$registry->loadArray($array['params']);
			$array['params'] = (string)$registry;
		}
		
		// Bind the rules.
		if (isset($array['rules']) && is_array($array['rules'])) {
			$rules = new JRules($array['rules']);
			$this->setRules($rules);
		}

		return parent::bind($array, $ignore);
	}
	
	 function check()
	{
	   
		if(  $this->catid == 0 ) {
			
		    $this->setError( JText::_('Please select a category') );
			return false;
			
		}
		
		$user =& JFactory::getUser();
		$this->modified_by = $user->get('id');
		$this->modified = date('Y-m-d H:i:s');
		
		
		if ( !$this->id ) {	
        	$this->author = $user->get('id');
			$this->created = date('Y-m-d H:i:s');
			// if new item, order last in appropriate group
			$where = 'catid = ' . (int) $this->catid ;
			$this->ordering = $this->getNextOrder( $where );
			$params = &JComponentHelper::getParams( 'com_jmonoslideshow' );
			if ($params->get( 'auto_publication', 1) == 1 ) $this->published = 1; else $this->published = 0;
        }
		
		return true;
	}
	
		public function store($updateNulls = false) 
	{
		$date = JFactory::getDate();
		$user = JFactory::getUser();
		$db = JFactory::getDbo();
		if ($this->id) 
		{
			// Existing item
			$this->modified = $date->toMySQL();
			$this->modified_by = $user->get('id');
			$table = JTable::getInstance('Media', 'JmonoslideshowTable');
			$table->load($this->id);
			$change_ordering = $table->catid != $this->catid;
			$imageid = $this->id;
		}
		else
		{
			// New entry. An entry created and created_by field can be set by the user,
			// so we don't touch either of these if they are set.

			if (!intval($this->created)) 
			{
				$this->created = $date->toMySQL();
			}
			if (empty($this->author)) 
			{
				$this->author = $user->get('id');
			}
			$change_ordering = true;
			
			$imageid = $db->insertid();
		}
		if ($change_ordering) 
		{
			// Set the ordering to be at the end of the catagory
			$query = $db->getQuery(true);
			$query->select('MAX(ordering)');
			$query->from('#__monoslideshow');
			$query->where('id=' . (int)$this->id);
			$db->setQuery($query);
			$max = $db->loadResult();
			$this->ordering = $max + 1;
		}
		
		$this->type = JRequest::getVar( 'type', '' , 'POST' );
		if ($this->rss == 1) $this->type = 3;
		$upload_etat = JRequest::getVar( 'upload_etat', '' , 'POST' );
		$upload_etat_thumb = JRequest::getVar( 'upload_etat_thumb', '' , 'POST' );
		
		$db =& JFactory::getDBO();;
		$oldFilename = JRequest::getVar( 'oldFilename', '' , 'POST' );
		if ($oldFilename != "" && $this->rss == 1)
					{
					$searchpath = JPATH_SITE . DS . "media". DS ."com_jmonoslideshow". DS ."upload";
					$files = JFolder::files($searchpath, $oldFilename, true, true);
					
					foreach ($files as $file) {
						   JFile::delete($file);
					}
					$this->filename = "";
					}
		if ($upload_etat_thumb == "ok" || $upload_etat == "ok")
			{			
				require_once JPATH_COMPONENT_ADMINISTRATOR.DS.'library/ThumbLib.inc.php';
				jimport('joomla.filesystem.folder');
				jimport('joomla.filesystem.file');
				
				
				$upload_tmp = JPATH_CACHE.DS;
				
				// Set FTP credentials, if given
				jimport('joomla.client.helper');
				JClientHelper::setCredentialsFromRequest('ftp');
				
				//Parameters component
				$params = &JComponentHelper::getParams( 'com_jmonoslideshow' );
				$maxPreviewWidth = $params->get( 'width_big_image', '800' );
				$maxPreviewHeight = $params->get( 'height_big_image', '800' );
				$maxThumbnailWidth = $params->get('width_vignette', '120');
				$maxThumbnailHeight = $params->get( 'height_vignette', '90' );
				$jpgQuality = $params->get( 'qualtiy_image', '75' );
				$options = array('jpegQuality' => $jpgQuality);
				
				$base_upload_dir = JPATH_ROOT.DS . 'media' . DS . 'com_jmonoslideshow' . DS . 'upload' ;
				if ( !JFolder::exists($base_upload_dir) ) { JFolder::create($base_upload_dir); }
				if ( !JFolder::exists($base_upload_dir.DS.'50-50') ) { JFolder::create($base_upload_dir.DS.'50-50'); }
				if ( !JFolder::exists($base_upload_dir.DS.'30-30') ) { JFolder::create($base_upload_dir.DS.'30-30'); }
				if ( !JFolder::exists($base_upload_dir.DS.$maxThumbnailWidth.'-'.$maxThumbnailHeight) ) { JFolder::create($base_upload_dir.DS.$maxThumbnailWidth.'-'.$maxThumbnailHeight); }
			}
		
		if ($upload_etat_thumb == "ok")
			{
		
				$thumbName = JRequest::getVar( 'upload_thumb_name', '' , 'POST' );
				$namethumb = JFile::stripExt($thumbName);
				$filethumbExtension = strtolower(JFile::getExt( $thumbName ));
				$newNameThumb = JApplication::stringURLSafe($namethumb)."-".rand().".".$filethumbExtension;
				$this->thumbname = $newNameThumb;
				
				//create a thumbnails
				$thumb = PhpThumbFactory::create($upload_tmp.DS.''.$thumbName, $options);
				$thumb->resize(50, 50);
				$thumb->save($base_upload_dir.DS.'50-50/'.$newNameThumb);
				
				$thumb = PhpThumbFactory::create($upload_tmp.DS.''.$thumbName, $options);
				$thumb->resize(30, 30);
				$thumb->save($base_upload_dir.DS.'30-30/'.$newNameThumb);
				
				$thumb = PhpThumbFactory::create($upload_tmp.DS.''.$thumbName, $options);
				$thumb->resize($maxThumbnailWidth, $maxThumbnailHeight);
				$thumb->save($base_upload_dir.DS.$maxThumbnailWidth.'-'.$maxThumbnailHeight.'/'.$newNameThumb);
				if (JFile::exists($base_upload_dir.DS."".$newNameThumb)) { JFile::delete($base_upload_dir.DS."".$newNameThumb); }
				JFile::move($upload_tmp.DS.$thumbName, $base_upload_dir.DS."".$newNameThumb);
				
				$oldthumbFilename = JRequest::getVar( 'oldthumbFilename', '' , 'POST' );
				
				if ($oldthumbFilename != "")
					{
					$searchpath = JPATH_SITE . DS . "media". DS ."com_jmonoslideshow". DS ."upload";
					$files = JFolder::files($searchpath, $oldthumbFilename, true, true);
					
					foreach ($files as $file) {
						   JFile::delete($file);
					}
					}
				
			}
		
		
		if ($upload_etat == "ok")
			{
		
			
			
			
			
			$fileName = JRequest::getVar( 'upload_media_name', '' , 'POST' );
			$newextension = JRequest::getVar( 'extension', '' , 'POST' );
			$type = JRequest::getVar( 'type', '' , 'POST' );

			
			$name = JFile::stripExt($fileName);
			$fileExtension = strtolower(JFile::getExt( $fileName ));
			$newName = JApplication::stringURLSafe($name)."-".rand().".".$fileExtension;
			$this->filename = $newName;
			
			
			
			
			
			if ($type == 0)
				{
				//$imageupload = PhpThumbFactory::create(JPATH_SITE.DS.'images' . DS . 'monoslideshow' . DS . 'tmp'.DS.$fileName, $options);
				
				//image resized
				//$imageupload->resize($maxPreviewWidth, $maxPreviewHeight);
				//$imageupload->save($base_upload_dir.DS.''.$row->id.'.jpg', 'jpg');
				
				//create a thumbnails
				$thumb = PhpThumbFactory::create($upload_tmp.DS.''.$fileName, $options);
				$thumb->resize(50, 50);
				$thumb->save($base_upload_dir.DS.'50-50/'.$newName);
				
				$thumb = PhpThumbFactory::create($upload_tmp.DS.''.$fileName, $options);
				$thumb->resize(30, 30);
				$thumb->save($base_upload_dir.DS.'30-30/'.$newName);
				
				$thumb = PhpThumbFactory::create($upload_tmp.DS.''.$fileName, $options);
				$thumb->resize($maxThumbnailWidth, $maxThumbnailHeight);
				$thumb->save($base_upload_dir.DS.$maxThumbnailWidth.'-'.$maxThumbnailHeight.'/'.$newName);
				//delete temp image
				//if (!JFile::delete($upload_tmp."/".$fileName)) return false;
				
				if (JFile::exists($base_upload_dir.DS."".$newName)) { JFile::delete($base_upload_dir.DS."".$newName); }
				JFile::move($upload_tmp.DS.$fileName, $base_upload_dir.DS."".$newName);
				}
				else
				{
				$fileExtension = strtolower(JFile::getExt( $fileName ));
				if (!$this->id) 
					{
						if ($type == 1) $selectThumb = "flash"; else $selectThumb = "video";
						$newNameThumb = JApplication::stringURLSafe($selectThumb)."-".rand().".png";
						$this->thumbname = $newNameThumb;
						//create a thumbnails
						$thumb = PhpThumbFactory::create(JPATH_SITE.DS.media.DS.com_jmonoslideshow.DS.images.DS.admin.DS.$selectThumb.'.png', $options);
						$thumb->resize($maxThumbnailWidth, $maxThumbnailHeight);
						$thumb->save($base_upload_dir.DS.$maxThumbnailWidth.'-'.$maxThumbnailHeight.'/'.$newNameThumb);
					}
				if (JFile::exists($base_upload_dir.DS."".$newName)) { JFile::delete($base_upload_dir.DS."".$newName); }
				JFile::move($upload_tmp.DS.$fileName, $base_upload_dir.DS."".$newName);	
				}
				
				if ($oldFilename != "")
					{
					$searchpath = JPATH_SITE . DS . "media". DS ."com_jmonoslideshow". DS ."upload";
					$files = JFolder::files($searchpath, $oldFilename, true, true);
					
					foreach ($files as $file) {
						   JFile::delete($file);
					}
					}
				
				
			}
		

		// Attempt to store the data.
		if (parent::store($updateNulls)) 
		{
			if (isset($table)) 
			{
				$table->reorder('id=' . $table->id);
			}
			return true;
		}
		return false;
	}
}
?>